package viewcontroller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import utils.CartItem;

import com.example.lastprojectbeautiplus.R;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalOAuthScopes;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalProfileSharingActivity;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.squareup.picasso.Picasso;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyCartFragment extends Fragment {
	public MyCartFragment() {
	}

	public static final int ONSHIP_PAYMENT = 1;
	public static final int ONLINE_PAYMENT = 2;
	private SQLiteDatabase dbCart, dbConfirm, dbAccount;
	private Cursor csCart, csAccount;
	private LinearLayout listViewCart;
	private ArrayList<CartItem> productList;
	private TextView tvKind, tvAmount, tvTotal;
	private Button btnPayOnShip, btnPayOnline;
	private TableLayout table;
	private double total = 0;
	private int amount = 0;
	private int count = 0;
	int width, height;
	private String paypalTransaction;
	private String paymentTime;
	private static final String TAG = "Payment Online by Paypal";
	private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
	// note that these credentials will differ between live & sandbox
	// environments.
	private static final String CONFIG_CLIENT_ID = "AbY9eBCD7aih8MK1c4Aj-1oFK4j0Z8vN2lh0bX6PMGlTUWJYzdBIs4t6GSQu";

	private static final int REQUEST_CODE_PAYMENT = 1;
	private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
	private static final int REQUEST_CODE_PROFILE_SHARING = 3;

	private static PayPalConfiguration config = new PayPalConfiguration()
			.environment(CONFIG_ENVIRONMENT)
			.clientId(CONFIG_CLIENT_ID)
			.merchantName("Beauty Plus Payment")
			.merchantPrivacyPolicyUri(
					Uri.parse("https://www.example.com/privacy"))
			.merchantUserAgreementUri(
					Uri.parse("https://www.example.com/legal"));

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.fragment_my_cart, container,
				false);
		DisplayMetrics metrics = rootView.getResources().getDisplayMetrics();
		width = metrics.widthPixels;
		height = metrics.heightPixels;
		// Create SQLite
		createCartTable();
		createAccountTable();
		paypalConfirm();
		productList = new ArrayList<CartItem>();
		// lvCart = (ListView) rootView.findViewById(R.id.lvCartList);
		listViewCart = (LinearLayout) rootView.findViewById(R.id.listViewCart);
		tvKind = (TextView) rootView.findViewById(R.id.tvNumberOfKind);
		tvAmount = (TextView) rootView.findViewById(R.id.tvAmountProduct);
		tvTotal = (TextView) rootView.findViewById(R.id.tvTotalExpend);
		btnPayOnShip = (Button) rootView.findViewById(R.id.btnPayOnShip);
		btnPayOnline = (Button) rootView.findViewById(R.id.btnPayOnline);
		table = (TableLayout) rootView.findViewById(R.id.tableLayout);
		TextView tvSize = (TextView) rootView.findViewById(R.id.tvMakeSize);
		callCartList();
		tvSize.getLayoutParams().width = width * 2 / 3;
		tvKind.getLayoutParams().width = width / 3;
		tvKind.setText("" + productList.size());
		tvAmount.setText("" + amount);
		tvTotal.setText((int) total + " VN�?");

		Intent intent = new Intent(getActivity(), PayPalService.class);
		intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
		getActivity().startService(intent);
		btnPayOnShip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				csAccount = dbAccount.rawQuery("SELECT * FROM ThisAccount",
						null);
				if (csAccount.getCount() == 0) {
					Toast.makeText(getActivity(),
							"Bạn phải đăng nhập trước khi thanh toán",
							Toast.LENGTH_SHORT).show();
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							getActivity());
					builder.setTitle("THÔNG BÁO")
							.setMessage(
									"Bạn lựa ch�?n hình thức thanh toán trực tiếp!"
											+ "\nBạn sẽ thanh toán trực tiếp với nhân viên vận chuyển sau khi nhận được hàng"
											+ " và không phải chi trả thêm bất kì một khoản phí nào khác"
											+ "\nSau đây hãy cung cấp cho chúng tôi các thông tin chính xác để nhận hàng"
											+ "\nChúc bạn vui vẻ!")
							.setPositiveButton("Điền thông tin vận chuyển",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											Intent paymentIntent = new Intent(
													getActivity(),
													SlideMenu.class);
											paymentIntent.putExtra("FromCart",
													ONSHIP_PAYMENT);
											getActivity().startActivity(
													paymentIntent);
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
		btnPayOnline.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				csAccount = dbAccount.rawQuery("SELECT * FROM ThisAccount",
						null);
				if (csAccount.getCount() == 0) {
					Toast.makeText(getActivity(),
							"Bạn phải đăng nhập trước khi thanh toán",
							Toast.LENGTH_SHORT).show();
				} else {
					PayPalPayment thingToBuy = getStuffToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
					Intent intent = new Intent(getActivity(),
							PaymentActivity.class);
					intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
					startActivityForResult(intent, REQUEST_CODE_PAYMENT);
				}

			}
		});
		return rootView;
	}

	private PayPalPayment getStuffToBuy(String paymentIntent) {
		// --- include an item list, payment amount details
		PayPalItem[] items = new PayPalItem[count];
		for (int i = 0; i < count; i++) {
			items[i] = new PayPalItem(productList.get(i).getName(), productList
					.get(i).getQuantity(), new BigDecimal(productList.get(i)
					.getPrice()).divide(new BigDecimal("21330.00"), 2,
					RoundingMode.CEILING), "USD", "sku-" + i);
		}
		BigDecimal subtotal = PayPalItem.getItemTotal(items);
		BigDecimal shipping = new BigDecimal("0.00");
		BigDecimal tax = new BigDecimal("00.00");
		PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(
				shipping, subtotal, tax);
		BigDecimal amount = subtotal.add(shipping).add(tax);
		PayPalPayment payment = new PayPalPayment(amount, "USD", "Beauty Plus",
				paymentIntent);
		payment.items(items).paymentDetails(paymentDetails);

		// --- set other optional fields like invoice_number, custom field, and
		// soft_descriptor
		payment.custom("This is text that will be associated with the payment that the app can use.");

		return payment;
	}

	public void onFuturePaymentPressed(View pressed) {
		Intent intent = new Intent(getActivity(),
				PayPalFuturePaymentActivity.class);

		startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
	}

	public void onProfileSharingPressed(View pressed) {
		Intent intent = new Intent(getActivity(),
				PayPalProfileSharingActivity.class);
		intent.putExtra(PayPalProfileSharingActivity.EXTRA_REQUESTED_SCOPES,
				getOauthScopes());
		startActivityForResult(intent, REQUEST_CODE_PROFILE_SHARING);
	}

	private PayPalOAuthScopes getOauthScopes() {
		/*
		 * create the set of required scopes Note: see
		 * https://developer.paypal.com
		 * /docs/integration/direct/identity/attributes/ for mapping between the
		 * attributes you select for this app in the PayPal developer portal and
		 * the scopes required here.
		 */
		Set<String> scopes = new HashSet<String>(Arrays.asList(
				PayPalOAuthScopes.PAYPAL_SCOPE_EMAIL,
				PayPalOAuthScopes.PAYPAL_SCOPE_ADDRESS));
		return new PayPalOAuthScopes(scopes);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				PaymentConfirmation confirm = data
						.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
				if (confirm != null) {
					try {
						String jsonPaypal = confirm.toJSONObject().toString();
						JSONObject paypalObject = new JSONObject(jsonPaypal);
						JSONObject paypalResponse = paypalObject
								.getJSONObject("response");
						paypalTransaction = paypalResponse.getString("id");
						paymentTime = paypalResponse.getString("create_time");
						Log.i(TAG, confirm.toJSONObject().toString(4));
						Log.i(TAG, confirm.getPayment().toJSONObject()
								.toString(4));
						/*
						 * TODO: send 'confirm' (and possibly
						 * confirm.getPayment() to your server for verification
						 * or consent completion. See
						 * https://developer.paypal.com
						 * /webapps/developer/docs/integration
						 * /mobile/verify-mobile-payment/ for more details. For
						 * sample mobile backend interactions, see
						 */
						Toast.makeText(getActivity(),
								"Bạn đã thanh toán thành công qua Paypal",
								Toast.LENGTH_LONG).show();

					} catch (JSONException e) {
						Log.e(TAG, "an extremely unlikely failure occurred: ",
								e);
					}
				}
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.i(TAG, "The user canceled.");
			} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
				Log.i(TAG,
						"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
			}
		} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				PayPalAuthorization auth = data
						.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
				if (auth != null) {
					try {
						Log.i("FuturePaymentExample", auth.toJSONObject()
								.toString(4));

						String authorization_code = auth.getAuthorizationCode();
						Log.i("FuturePaymentExample", authorization_code);

						sendAuthorizationToServer(auth);
						Toast.makeText(getActivity(),
								"Future Payment code received from PayPal",
								Toast.LENGTH_LONG).show();

					} catch (JSONException e) {
						Log.e("FuturePaymentExample",
								"an extremely unlikely failure occurred: ", e);
					}
				}
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.i("FuturePaymentExample", "The user canceled.");
			} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
				Log.i("FuturePaymentExample",
						"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
			}
		} else if (requestCode == REQUEST_CODE_PROFILE_SHARING) {
			if (resultCode == Activity.RESULT_OK) {
				PayPalAuthorization auth = data
						.getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
				if (auth != null) {
					try {
						Log.i("ProfileSharingExample", auth.toJSONObject()
								.toString(4));
						String authorization_code = auth.getAuthorizationCode();
						Log.i("ProfileSharingExample", authorization_code);

						sendAuthorizationToServer(auth);
						Toast.makeText(getActivity(),
								"Profile Sharing code received from PayPal",
								Toast.LENGTH_LONG).show();

					} catch (JSONException e) {
						Log.e("ProfileSharingExample",
								"an extremely unlikely failure occurred: ", e);
					}
				}
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.i("ProfileSharingExample", "The user canceled.");
			} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
				Log.i("ProfileSharingExample",
						"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
			}
		}
	}

	private void sendAuthorizationToServer(PayPalAuthorization authorization) {

		/*
		 * TODO: Send the authorization response to your server, where it can
		 * exchange the authorization code for OAuth access and refresh tokens.
		 * 
		 * Your server must then store these tokens, so that your server code
		 * can execute payments for this user in the future.
		 * 
		 * A more complete example that includes the required app-server to
		 * PayPal-server integration is available from
		 */

	}

	public void onFuturePaymentPurchasePressed(View pressed) {
		// Get the Application Correlation ID from the SDK
		String correlationId = PayPalConfiguration
				.getApplicationCorrelationId(getActivity());

		Log.i("FuturePaymentExample", "Application Correlation ID: "
				+ correlationId);

		// TODO: Send correlationId and transaction details to your server for
		// processing with
		// PayPal...
		Toast.makeText(getActivity(), "App Correlation ID received from SDK",
				Toast.LENGTH_LONG).show();
	}

	private void callCartList() {
		csCart = dbCart.rawQuery("SELECT * FROM TableMyCart", null);
		csCart.moveToLast();
		count = csCart.getCount();
		total = 0;
		amount = 0;
		if (count > 0) {
			for (int i = 0; i < count; i++) {
				CartItem cartRow = new CartItem();
				cartRow.setProductID(csCart.getInt(csCart
						.getColumnIndex("productID")));
				cartRow.setBrand(csCart.getString(csCart
						.getColumnIndex("productBrand")));
				cartRow.setName(csCart.getString(csCart
						.getColumnIndex("productName")));
				cartRow.setColor(csCart.getString(csCart
						.getColumnIndex("color")));
				cartRow.setSize(csCart.getString(csCart.getColumnIndex("size")));
				cartRow.setQuantity(csCart.getInt(csCart
						.getColumnIndex("quantity")));
				cartRow.setImagePath(csCart.getString(csCart
						.getColumnIndex("imgPath")));
				cartRow.setPrice(csCart.getDouble(csCart
						.getColumnIndex("price")));
				productList.add(cartRow);
				amount = amount
						+ csCart.getInt(csCart.getColumnIndex("quantity"));
				total = total
						+ csCart.getInt(csCart.getColumnIndex("quantity"))
						* csCart.getDouble(csCart.getColumnIndex("price"));

				csCart.moveToPrevious();
			}
			// execute cart list
			listViewCart.removeAllViews();
			for (int i = 0; i < productList.size(); i++) {
				LayoutInflater inflaterlayout = null;
				inflaterlayout = (LayoutInflater) getActivity()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View mLinearView = inflaterlayout.inflate(
						R.layout.listview_cart_item, null);
				ImageView imgProduct = (ImageView) mLinearView
						.findViewById(R.id.imgProduct);
				TextView tvBrand = (TextView) mLinearView
						.findViewById(R.id.tvBrand);
				TextView tvName = (TextView) mLinearView
						.findViewById(R.id.tvName);
				TextView tvSize = (TextView) mLinearView
						.findViewById(R.id.tvSize);
				TextView tvColor = (TextView) mLinearView
						.findViewById(R.id.tvColor);
				TextView tvQuantity = (TextView) mLinearView
						.findViewById(R.id.tvQuantity);
				TextView tvPrice = (TextView) mLinearView
						.findViewById(R.id.tvPrice);

				String url = productList.get(i).getImagePath();
				imgProduct.getLayoutParams().width = width / 4;
				imgProduct.getLayoutParams().height = height / 4;
				Picasso.with(getActivity()).load(url)
						.placeholder(R.drawable.image_wait)
						.error(R.drawable.error_loading).into(imgProduct);

				tvBrand.setText(productList.get(i).getBrand());
				tvName.setText(productList.get(i).getName());
				tvSize.setText(productList.get(i).getSize());
				tvColor.setText(productList.get(i).getColor());
				tvQuantity.setText(productList.get(i).getQuantity() + "");
				tvPrice.setText((productList.get(i).getPrice() + "").replace(
						".0", " VN�?"));
				@SuppressWarnings("deprecation")
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				lp.leftMargin = 20;
				lp.rightMargin = 20;
				lp.bottomMargin = 10;
				lp.topMargin = 10;
				mLinearView.setLayoutParams(lp);
				listViewCart.addView(mLinearView);
				listViewCart.invalidate();
				final int j = i;
				mLinearView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

					}
				});
				mLinearView.setOnLongClickListener(new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						// TODO Auto-generated method stub
						AlertDialog.Builder builder = new AlertDialog.Builder(
								getActivity());
						builder.setMessage(
								"Bạn muốn xóa vật phẩm này ra kh�?i gi�? hàng?")
								.setCancelable(false)
								.setPositiveButton("Đồng ý",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dbCart.execSQL("DELETE FROM TableMyCart WHERE color ='"
														+ productList.get(j)
																.getColor()
														+ "' AND size ='"
														+ productList.get(j)
																.getSize()
														+ "';");
												productList.remove(j);
												callCartList();
												Fragment frg = null;
												frg = getFragmentManager()
														.findFragmentById(
																R.id.frame_container);
												FragmentTransaction ft = getFragmentManager()
														.beginTransaction();
												ft.detach(frg);
												ft.attach(frg);
												ft.commit();

											}
										})
								.setNegativeButton("Hủy",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dialog.cancel();
											}
										});
						AlertDialog alert = builder.create();
						alert.show();
						return false;
					}
				});
				mLinearView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(),
								SlideMenu.class);
						intent.putExtra("FromProductList", productList.get(j)
								.getProductID());
						getActivity().startActivity(intent);
					}
				});
			}
		} else {
			listViewCart.removeAllViews();
			LayoutInflater inflaterlayout = null;
			inflaterlayout = (LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			View mLinearView = inflaterlayout
					.inflate(R.layout.empty_cart, null);
			listViewCart.addView(mLinearView);
			table.setVisibility(View.INVISIBLE);
			btnPayOnline.setVisibility(View.INVISIBLE);
			btnPayOnShip.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onDestroy() {
		// Stop service when done
		getActivity().stopService(
				new Intent(getActivity(), PayPalService.class));
		super.onDestroy();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		paypalConfirm();
		if (paypalTransaction != null) {
			dbConfirm.execSQL("INSERT INTO TableConfirm VALUES('"
					+ paypalTransaction + "','" + paymentTime + "');");
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("THÔNG B�?O")
					.setMessage(
							"Bạn lựa ch�?n hình thức thanh toán trước qua Paypal"
									+ "\nBạn sẽ không phải thanh toán bất kì một khoản phí nào khác khi nhận"
									+ " hàng từ nhân viên giao hàng"
									+ "\nSau đây hãy cung cấp cho chúng tôi thông tin chính xác để nhận hàng"
									+ "\nChúc bạn vui vẻ!")
					.setPositiveButton("Điền thông tin vận chuyển",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Intent paymentIntent = new Intent(
											getActivity(), SlideMenu.class);
									paymentIntent.putExtra("FromCart",
											ONLINE_PAYMENT);
									getActivity().startActivity(paymentIntent);
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}

	private void createCartTable() {
		dbCart = getActivity().openOrCreateDatabase("TableMyCart",
				android.content.Context.MODE_PRIVATE, null);
		String sqlCart = "CREATE TABLE IF NOT EXISTS TableMyCart(productID INT, productBrand VARCHAR, productName VARCHAR,"
				+ " quantity INT, color VARCHAR, size VARCHAR, imgPath VARCHAR, price DOUBLE);";
		dbCart.execSQL(sqlCart);
	}

	private void paypalConfirm() {
		dbConfirm = getActivity().openOrCreateDatabase("TableConfirm",
				android.content.Context.MODE_PRIVATE, null);
		String sqlConfirm = "CREATE TABLE IF NOT EXISTS TableConfirm(paypalTransaction VARCHAR, paymentTime VARCHAR);";
		dbConfirm.execSQL(sqlConfirm);
	}

	private void createAccountTable() {
		dbAccount = getActivity().openOrCreateDatabase("ThisAccount",
				android.content.Context.MODE_PRIVATE, null);
		String sqlAccount = "CREATE TABLE IF NOT EXISTS ThisAccount(userID INT, storeOwner INT);";
		dbAccount.execSQL(sqlAccount);
	}

}
